/*
--------------------------------------------------------------------------------
%include "/projects/hsieh_project/code_0_general/m_perc_by_var.sas" /source2;
%m_perc_by_var(ds_in= , ds_out= , var_in= , var_by= , var_unit= , var_out= , var_runif= );

var_in = variable used to create rank and percentile
var_by = by group
var_unit = basic unit of observation (e.g. firm, plant, etc)
var_out = variable name root
var_runif = random number used to break ties
--------------------------------------------------------------------------------
*/

%include "/projects/hsieh_project/code_0_general/m_rank_by_var.sas" /source2;

%macro m_perc_by_var(ds_in= , ds_out= , var_in= , var_by= , var_unit= , var_out= , var_runif=runif);

%put ds_in: &ds_in.;
%put ds_out: &ds_out.;
%put var_by: &var_by.;
%put var_unit: &var_unit.;
%put var_out: &var_out.;
%put var_runif: &var_runif.;


data &ds_out.;
  set &ds_in.;
  nvar_in=-&var_in.;
run;

proc sort data=&ds_out.;
  by &var_by. &var_unit.;
run;

proc means data=&ds_out. noprint;
  by &var_by. &var_unit.;
  output out=&ds_out.(drop=_type_ _freq_) sum(&var_in. nvar_in)=&var_in. nvar_in mean(&var_runif.)=&var_runif.;
run;

/* Rank by variable */
%m_rank_by_var(ds=&ds_out., var_by0=%bquote(&var_by.), var_by1=nvar_in, var_tie=&var_runif., var_rank=&var_out._rank);

/* Ensure that ds_out only has selected variables */
data &ds_out.;
  set &ds_out.;
  keep &var_by. &var_unit. &var_out._rank;
run;

/* Count total var_unit */
data &ds_out._n;
  set &ds_out.;
  &var_out._n=1;
run;

proc sort data=&ds_out._n;
  by &var_by.;
run;

proc means data=&ds_out._n noprint;
  by &var_by.;
  output out=&ds_out._n(drop=_type_ _freq_) sum(&var_out._n)=&var_out._n;
run;

proc sort data=&ds_out.;
  by &var_by.;
run;

/* Merge count of var_unit with ds_out */
data &ds_out.;
  merge &ds_out. &ds_out._n;
  by &var_by.;
run;

/* Calculate percentile and keep selected variables */
data &ds_out.;
  set &ds_out.;
  &var_out._perc=&var_out._rank/&var_out._n;
  keep &var_by. &var_unit. &var_out._rank &var_out._n &var_out._perc;
run;

%mend;

/* End of SAS file */
